<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Group;
use App\Models\Member;
use Illuminate\Http\Request;

class MemberController extends Controller
{

    //列表
    public function index(Request $request){
        $gid = (int)$request->get('gid',0);
        $userId = auth('api')->id();
        $params = [
            'uid' => $userId,
            'gid' => $gid,
        ];
        $lists = Member::getWList($params,['*']);
        foreach ($lists->items() as $item) {
            $item->group_name = Group::whereId($item->group_id)->value('name');
        }
        return $this->writeJson(0,$lists);
    }

    //详情
    public function info(Request $request)
    {
        $id = $request->get('id');
        $field = [
            '*'
        ];
        $info = Member::query()->select($field)
            ->where('id', $id)
            ->where('user_id', auth('api')->id())->with('user:id,city,province,country,avatar')->first()->makeHidden([
            'created_at',
            'updated_at'
        ])->toArray();
        return $this->success($info);
    }

    //更新
    public function update(Request $request)
    {
        $data = $request->all();
        $data['user_id'] = auth('api')->id();
        if($data['id']){
            $info = Member::where('user_id',$data['user_id'])->findOrFail($data['id']);
            $info->update($data);
            return $this->writeJson(0,null,'修改成功');
        }else{
            unset($data['id']);
            Member::create($data);
            return $this->writeJson(0,null,'新增成功');
        }
    }
}
